<?php

namespace app\admin\controller;

use app\common\controller\Backend;

/**
 * 优惠券
 *
 * @icon fa fa-circle-o
 */
class Coupon extends Backend {

    /**
     * Coupon模型对象
     * @var \app\admin\model\Coupon
     */
    protected $model = null;

    public function _initialize() {
        parent::_initialize();
        $this->model = new \app\admin\model\Coupon;
        $this->view->assign("receiveTypeList", $this->model->getReceiveTypeList());
        $this->view->assign("rangeList", $this->model->getRangeList());
        $this->view->assign('expiryTypeList', $this->model->getExpiryTypeList());
    }

    public function index() {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            foreach ($list as &$row) {
                $received = db('user_coupon')->where(['coupon_id' => $row['coupon_id']])->count();
                $used = db('user_coupon')->where(['coupon_id' => $row['coupon_id'], 'status' => 1])->count();
                
                $row['received'] = isset($received) ? $received : 0;
                $row['used'] = isset($used) ? $used : 0;
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add() {

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }

                    if ($params['range'] == 1) {
                        $params['relation_id'] = implode(',', $params['brand']);
                        unset($params['brand']);
                    }
                    if ($params['range'] == 2) {
                        $params['relation_id'] = implode(',', $params['cate']);
                        unset($params['cate']);
                    }


                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $brandList = \think\Db::name('goods_brand')->where(['is_deleted' => 0])->order('brand_id ASC')->select();
        $cateList = \think\Db::name('goods_cate')->where(['is_deleted' => 0])->order('cate_id ASC')->select();

        $this->assign('brandList', $brandList);
        $this->assign('cateList', $cateList);
        return $this->view->fetch();
    }

    public function edit($ids = NULL) {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }

                    if ($params['range'] == 1) {
                        $params['relation_id'] = implode(',', $params['brand']);
                        unset($params['brand']);
                    }
                    if ($params['range'] == 2) {
                        $params['relation_id'] = implode(',', $params['cate']);
                        unset($params['cate']);
                    }

                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $brandList = \think\Db::name('goods_brand')->where(['is_deleted' => 0])->order('brand_id ASC')->select();
        $cateList = \think\Db::name('goods_cate')->where(['is_deleted' => 0])->order('cate_id ASC')->select();
        
        $this->assign('brandList', $brandList);
        $this->assign('cateList', $cateList);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function show() {
        $id = input('ids');

        $coupon_info = db('coupon')->where('coupon_id', $id)->find();

        if ($coupon_info) {
            $title = '';
            $list = [];
            if ($coupon_info['range'] == 1) {
                $title = "适用品牌";

                $list = db('goods_brand')->field('brand_title as name')->where('brand_id', 'in', $coupon_info['relation_id'])->select();
            }

            if ($coupon_info['range'] == 2) {
                $title = "适用品类";

                $list = db('goods_cate')->field('cate_title as name')->where('cate_id', 'in', $coupon_info['relation_id'])->select();
            }

            $this->assign('list', $list);
            $this->assign('title', $title);
            $this->assign('info', $coupon_info);
        } else {
            $this->error('没有找到优惠券');
        }
        return $this->view->fetch();
    }

    public function stop() {
        $id = input('ids');
        $this->model->where(['coupon_id' => $id, 'status' => 1])->setField('status', 10);
        $this->success();
    }

    public function senduser() {
        $id = input('id');

        $user_ids = input('user_ids');

        $user_ids = explode(',', $user_ids);

        if (!is_array($user_ids)) {
            $this->error('数据不对');
        }

        foreach ($user_ids as $ids) {
            receiveCoupon($ids, $id);
        }

        $this->success('发放成功');
    }

}
